<!-- 首页 -->
<script>
import SubtitledSection from '@/components/layout/SubtitledSection.vue'
import SubtitledSectionLong from '@/components/layout/SubtitledSectionLong.vue'
import Head2 from '@/components/layout/Head2.vue'
import DeviceList from '@/components/layout/DeviceList.vue'
import AlarmList from '@/components/layout/AlarmList.vue'
import {caicon, select_equipmentv2, shebeilistv2, getcamera,getweather } from '@/request/api';
import chartline from '@/components/charts/Line/Line.vue'
import axios from 'axios';
import EZUIKit from 'ezuikit-js';
import * as echarts from 'echarts';

const detailDeviceListData = (DeviceList && typeof DeviceList.data === 'function') ? DeviceList.data() : {};
const DETAIL_TRACE_SHIPS = Array.isArray(detailDeviceListData.staticShips) ? detailDeviceListData.staticShips : [];
const DETAIL_TRACE_MAP = new Map();

DETAIL_TRACE_SHIPS.forEach(ship => {
  if (!ship || !ship.catchData) {
    return;
  }
  const shipName = ship.BACILITIES_NAME || ship.ship_name || ship.EQUIPMENT_NAME || '';
  ship.catchData.forEach(dayItem => {
    if (!dayItem || !dayItem.records) {
      return;
    }
    dayItem.records.forEach(record => {
      if (record && record.RFID) {
        DETAIL_TRACE_MAP.set(record.RFID, {
          record,
          shipName,
          ship,
          dayItem
        });
      }
    });
  });
});

export default {
  components: {
    SubtitledSection, //短标题框
    SubtitledSectionLong,//长标题框
    Head2,//头部
    DeviceList,
    //AlarmList,
    //chartline
  },
  data() {
    return {
      videoAddresses: [],
      SerialNumber: [],
      video_address: [],
      cameralist: [],
      base_id: "",
      shelist: [],
      jktokens: {
        value: ''
      },
      formattedData: [
        { label: '设备名称', value: '' },
        { label: '设备描述', value: '' },
        { label: '运行状态', value: '' },
        { label: '电压', value: '' },
        { label: '光照', value: '' },
        { label: '风速', value: '' },
        { label: '风向', value: '' },
        { label: '辐射', value: '' },
        { label: 'ORP', value: '' },
        { label: 'CON', value: '' },
      ],
      currentTime: '',
      miaoshu: { EQUIPMENT_NAME: '', INTRODUCE: '', Online_Voltage: '', state: '', LIGHT: '', WIND_SPEED: '', WIND_DIRECTION: '', RADIATION: '', ORP: '', CON: '', type: 1 },
      box: 0,
      zuobiaolist: [],
      shebeilist: {
        "water": [],
        "meteorological": [],
        "monitoring": []
      },
      equipmentID: '',
      lineData: [
        {
          name: "舱温一",
          data: [],
          xAxisData: [],
          data1: [],
          data2: [],
        }, {
          name: "舱温二",
          data: [],
          xAxisData: [],
          data1: [],
          data2: [],
        }, {
          name: "舱温三",
          data: [],
          xAxisData: [],
          data1: [],
          data2: [],
        }, {
          name: "舱温四",
          data: [],
          xAxisData: [],
          data1: [],
          data2: [],
        }
      ],
      videoSrc1: '',
      videoSrc2: '',
      // wetherinfo: {
      //   'wendu': {
      //     img: 'top-info-wd.png',
      //     value: '0'
      //   },
      //   'shidu': {
      //     img: 'top-info-xy.png',
      //     value: '0'
      //   },
      //   'fengxiang': {
      //     img: 'top-info-ql.png',
      //     value: '0'
      //   },
      //   'fengsu': {
      //     img: 'top-info-fs.png',
      //     value: '0'
      //   },
      //   'guangzhao': {
      //     img: 'top-info-yg.png',
      //     value: '0'
      //   },
      //   'jiangyuliang': {
      //     img: 'top-info-sd.png',
      //     value: '0'
      //   },
      //   'qiya': {
      //     img: 'top-info-qy.png',
      //     value: '0'
      //   }
      // },
      wetherinfo1: {
        'temperature': {
          img: 'top-info-wd.png',
          value: '0'
        },
        'humidity': {
          img: 'top-info-xy.png',
          value: '0'
        },
        'wind_direction': {
          img: 'top-info-ql.png',
          value: '0'
        },
        'wind_power': {
          img: 'top-info-fs.png',
          value: '0'
        }, 
        'guangzhao': {
          img: 'top-info-yg.png',
          value: '-'
        },
        'precipitation': {
          img: 'top-info-sd.png',
          value: '-'
        },
        'pressure': {
          img: 'top-info-qy.png',
          value: '-'
        } ,
      },
      selectid: 0,
      alertYuanList: [],
      TEM: 0,
      PH: 0,
      O2: 0,
      SALT: 0,
      CON: 0,
      HUMIDITY: 0,
      ATM: 0,
      RAINFALL: 0,
      markerBackgrounds: {
        '水质检测': require('@/assets/ui/position-text-bg.png'),
        '气象检测': require('@/assets/ui/position-text-bg2.png')
      },
      city: '上海',  // 直接设置城市为 "上海"
      livetianqi: null,  // 存储天气数据
      // 模拟渔场数据
      fisheryList: [
        { id: 1, name: '东海渔场', location: '29°30\'N, 122°15\'E' },
        { id: 2, name: '黄海渔场', location: '35°45\'N, 121°20\'E' },
        { id: 3, name: '南海渔场', location: '20°15\'N, 113°30\'E' },
        { id: 4, name: '舟山渔场', location: '30°00\'N, 122°00\'E' },
        { id: 5, name: '渤海渔场', location: '38°30\'N, 119°45\'E' },
        { id: 6, name: '长江口渔场', location: '31°15\'N, 121°45\'E' },
        { id: 7, name: '闽东渔场', location: '26°30\'N, 120°15\'E' },
        { id: 8, name: '北部湾渔场', location: '21°00\'N, 108°30\'E' }
      ],
      scrollTimer: null, // 自动滚动定时器
      scrollPosition: 0, // 滚动位置
      // 渔场捕捞量数据
      catchVolumeChart: null, // 捕捞量图表实例
      catchVolumeTimeRange: 'week', // 当前选择的时间范围：week, month, year, custom
      chartResizeHandler: null, // 图表resize事件处理器
      catchVolumeCustomDateRange: {
        startDate: '',
        endDate: ''
      },
      catchVolumeData: {
        // 近一周各渔场捕捞量
        week: [],
        // 近一月各渔场捕捞量
        month: [],
        // 近一年各渔场捕捞量
        year: [],
        // 自定义时间范围数据
        custom: []
      },
      // 分级捕捞量数据
      gradedCatchData: {
        // 近一周数据（7条）
        week: [],
        // 近一月数据（30条）
        month: [],
        // 近一年数据（12条）
        year: [],
        // 自定义时间范围数据
        custom: []
      },
      // 分级捕捞量饼状图相关
      gradedCatchChart: null, // 饼状图图表实例
      gradedCatchTimeRange: 'week', // 当前选择的时间范围：week, month, year, custom
      gradedCatchChartResizeHandler: null, // 图表resize事件处理器
      gradedCatchCustomDateRange: {
        startDate: '',
        endDate: ''
      },
      // 捕捞量折线图相关
      catchLineChart: null, // 折线图图表实例
      catchLineTimeRange: 'week', // 当前选择的时间范围：week, month, year, custom
      catchLineChartResizeHandler: null, // 图表resize事件处理器
      catchLineCustomDateRange: {
        startDate: '',
        endDate: ''
      },
      catchLineData: {
        // 近一周数据（每天）
        week: {
          dates: [],
          data: []
        },
        // 近一个月数据（每天）
        month: {
          dates: [],
          data: []
        },
        // 近一年数据（每月）
        year: {
          dates: [],
          data: []
        },
        // 自定义时间范围数据
        custom: {
          dates: [],
          data: []
        }
      },
      traceRecordsTable: [],
      traceModalTitle: '溯源记录',
      showTraceDialog: false,
      traceRecordMeta: null,
      traceDetailDialog: false,
      traceRecordDetail: '',
      traceTemperatureData: [],
      traceTemperatureChart: null,
      traceTransportTime: ''
    }
  },
  computed: {
    backgroundImage() {
      if (this.miaoshu.EQUIPMENT_TYPE === "水质检测") {
        return require('@/assets/ui/map-bg1.png');
      } else {
        return require('@/assets/ui/map-bg2.png');
      }
    },
    labelcolor() {
      return this.miaoshu.EQUIPMENT_TYPE == "水质检测" ? '#5CA0B1' : '#99BB6D'
    },
    valuecolor() {
      return this.miaoshu.EQUIPMENT_TYPE == "水质检测" ? '#c6e1e7' : '#e9f6d8'
    },
    miaoshuFormatted() {
      if (this.miaoshu.EQUIPMENT_TYPE == "水质检测") {
        const formattedData = [
          { label: '设备名称', value: this.miaoshu.EQUIPMENT_NAME },
          { label: '采集时间', value: this.miaoshu.ACQUISITION_TIME },
          { label: '设备描述', value: this.miaoshu.INTRODUCE },
          { label: '电压', value: this.miaoshu.VOLTAGE },
          { label: '状态', value: this.miaoshu.state },
          { label: 'ORP', value: this.miaoshu.ORP },
          { label: '电导', value: this.miaoshu.CON },
          { label: '温度', value: this.miaoshu.TEM },
          { label: 'PH', value: this.miaoshu.PH },
          { label: '含氧量', value: this.miaoshu.O2 },
          { label: '盐度', value: this.miaoshu.SALT }
        ];
        return formattedData;
      }
      else if (this.miaoshu.EQUIPMENT_TYPE == "气象检测") {
        const formattedData = [
          { label: '设备名称', value: this.miaoshu.EQUIPMENT_NAME },
          { label: '采集时间', value: this.miaoshu.ACQUISITION_TIME },
          { label: '设备描述', value: this.miaoshu.INTRODUCE },
          { label: '电压', value: this.miaoshu.VOLTAGE },
          { label: '状态', value: this.miaoshu.state },
          { label: '光照', value: this.miaoshu.LIGHT },
          { label: '风速', value: this.miaoshu.WIND_SPEED },
          { label: '风向', value: this.miaoshu.WIND_DIRECTION },
          { label: '辐射', value: this.miaoshu.RADIATION },
          { label: '温度', value: this.miaoshu.TEM },
          { label: '湿度', value: this.miaoshu.HUMIDITY }
          // { label: '气压', value: this.miaoshu.ATM },
          // { label: '雨量', value: this.miaoshu.RAINFALL }
        ];
        return formattedData;
      }
      return [];
    },
  },
  mounted() {
    this.renderMap();
    this.GetCamera();
    this.getlist();
    this.generateStaticTemperatureData(); // 静态数据展示用
    // this.startPolling(); // 开始定时请求数据
    this.getToken();
    this.GetWeather();
    // 启动渔场列表自动滚动
    this.$nextTick(() => {
      this.startFisheryAutoScroll();
      // 初始化捕捞量数据
      this.initCatchVolumeData();
      // 初始化捕捞量图表
      this.initCatchVolumeChart();
      // 初始化分级捕捞量数据
      this.initGradedCatchData();
      // 初始化分级捕捞量饼状图
      this.initGradedCatchChart();
      // 初始化捕捞量折线图数据
      this.initCatchLineData();
      // 初始化捕捞量折线图
      this.initCatchLineChart();
    });
  },
  beforeDestroy() {
    // 清理自动滚动定时器
    if (this.scrollTimer) {
      clearInterval(this.scrollTimer);
      this.scrollTimer = null;
    }
    // 清理图表实例
    if (this.catchVolumeChart) {
      this.catchVolumeChart.dispose();
      this.catchVolumeChart = null;
    }
    // 移除窗口resize监听器
    if (this.chartResizeHandler) {
      window.removeEventListener('resize', this.chartResizeHandler);
      this.chartResizeHandler = null;
    }
    // 清理分级捕捞量饼状图实例
    if (this.gradedCatchChart) {
      this.gradedCatchChart.dispose();
      this.gradedCatchChart = null;
    }
    // 移除分级捕捞量饼状图resize监听器
    if (this.gradedCatchChartResizeHandler) {
      window.removeEventListener('resize', this.gradedCatchChartResizeHandler);
      this.gradedCatchChartResizeHandler = null;
    }
    // 清理捕捞量折线图实例
    if (this.catchLineChart) {
      this.catchLineChart.dispose();
      this.catchLineChart = null;
    }
    // 移除捕捞量折线图resize监听器
    if (this.catchLineChartResizeHandler) {
      window.removeEventListener('resize', this.catchLineChartResizeHandler);
      this.catchLineChartResizeHandler = null;
    }
    this.disposeTraceChart();
  },
  methods: {
    handleTraceSearch(keyword) {
      const term = keyword ? keyword.trim() : '';
      if (!term) {
        if (this.$message && this.$message.warning) {
          this.$message.warning('请输入RFID');
        }
        return;
      }
      const match = DETAIL_TRACE_MAP.get(term);
      if (!match) {
        if (this.$message && this.$message.warning) {
          this.$message.warning('未找到该RFID的溯源记录');
        }
        return;
      }
      const recordCopy = Object.assign({}, match.record);
      this.traceRecordsTable = [recordCopy];
      this.traceRecordMeta = match;
      this.traceModalTitle = `${recordCopy.ship_name || match.shipName || '溯源记录'} - RFID ${recordCopy.RFID}`;
      this.showTraceDialog = true;
    },
    onTraceDialogClose() {
      this.showTraceDialog = false;
      this.traceRecordsTable = [];
      this.traceRecordMeta = null;
      this.traceDetailDialog = false;
      this.traceRecordDetail = '';
      this.traceTemperatureData = [];
      this.traceTransportTime = '';
      this.disposeTraceChart();
    },
    openTraceRecordDetail(record) {
      this.traceRecordDetail = record && record.details ? record.details : '暂无详情';
      let parsed = [];
      if (record && record.details) {
        try {
          parsed = JSON.parse(record.details);
        } catch (e) {
          parsed = [];
        }
      }
      this.traceTemperatureData = Array.isArray(parsed) ? parsed : [];
      const transportTime = record && record.transport_time ? String(record.transport_time).trim() : '';
      this.traceTransportTime = transportTime;
      this.traceDetailDialog = true;
      if (this.traceTemperatureData.length > 0) {
        this.$nextTick(() => {
          this.initTraceTemperatureChart();
        });
      } else {
        this.traceTransportTime = '';
        this.disposeTraceChart();
      }
    },
    closeTraceDetailDialog() {
      this.traceDetailDialog = false;
      this.traceRecordDetail = '';
      this.traceTemperatureData = [];
      this.traceTransportTime = '';
      this.disposeTraceChart();
    },
    initTraceTemperatureChart() {
      if (!this.traceTemperatureData || this.traceTemperatureData.length === 0) {
        return;
      }
      const chartContainer = this.$refs.traceTemperatureChart;
      if (!chartContainer) {
        return;
      }
      const currentTransportTime = this.traceTransportTime;
      this.disposeTraceChart();
      this.traceTransportTime = currentTransportTime;
      this.traceTemperatureChart = echarts.init(chartContainer);
      const times = this.traceTemperatureData.map(item => item.time);
      const temperatures = this.traceTemperatureData.map(item => item.temperature);
      const parseTimestamp = (value) => {
        if (!value) return NaN;
        const normalized = String(value).replace(/-/g, '/').replace('T', ' ');
        const date = new Date(normalized);
        return date.getTime();
      };
      let transportMarkLine = null;
      let transportIndex = -1;
      if (this.traceTransportTime) {
        const normalizedTransport = this.traceTransportTime;
        const transportTimestamp = parseTimestamp(normalizedTransport);
        if (!Number.isNaN(transportTimestamp)) {
          transportIndex = times.indexOf(normalizedTransport);
          if (transportIndex === -1) {
            const insertIndex = times.findIndex(time => parseTimestamp(time) > transportTimestamp);
            const getNumber = (val) => {
              if (val === null || val === undefined || val === '') {
                return null;
              }
              const num = Number(val);
              return Number.isNaN(num) ? null : num;
            };
            const interpolateTemperature = (prevIdx, nextIdx) => {
              const prevVal = prevIdx >= 0 ? getNumber(temperatures[prevIdx]) : null;
              const nextVal = nextIdx < temperatures.length ? getNumber(temperatures[nextIdx]) : null;
              const prevTime = prevIdx >= 0 ? parseTimestamp(times[prevIdx]) : NaN;
              const nextTime = nextIdx < times.length ? parseTimestamp(times[nextIdx]) : NaN;
              if (prevVal !== null && nextVal !== null && !Number.isNaN(prevTime) && !Number.isNaN(nextTime) && nextTime !== prevTime) {
                const ratio = (transportTimestamp - prevTime) / (nextTime - prevTime);
                const interpolated = prevVal + (nextVal - prevVal) * Math.min(Math.max(ratio, 0), 1);
                return Number(interpolated.toFixed(2));
              }
              if (prevVal !== null) return prevVal;
              if (nextVal !== null) return nextVal;
              return getNumber(temperatures[temperatures.length - 1]);
            };
            let transportTemp;
            if (insertIndex === -1) {
              transportTemp = interpolateTemperature(temperatures.length - 1, temperatures.length - 1);
              times.push(normalizedTransport);
              temperatures.push(transportTemp);
              transportIndex = times.length - 1;
            } else {
              transportTemp = interpolateTemperature(insertIndex - 1, insertIndex);
              times.splice(insertIndex, 0, normalizedTransport);
              temperatures.splice(insertIndex, 0, transportTemp);
              transportIndex = insertIndex;
            }
          }
          if (transportIndex !== -1) {
            transportMarkLine = {
              symbol: 'none',
              data: [
                {
                  xAxis: normalizedTransport,
                  lineStyle: {
                    color: '#FFD04B',
                    type: 'dashed',
                    width: 1.5
                  },
                  label: {
                    formatter: '转运时间',
                    color: '#FFD04B',
                    fontWeight: 'bold'
                  }
                }
              ]
            };
          }
        }
      }
      const beforeAreaStyle = {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(67, 200, 255, 0.3)' },
            { offset: 1, color: 'rgba(67, 200, 255, 0.05)' }
          ]
        }
      };
      const afterAreaStyle = {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(255, 129, 96, 0.35)' },
            { offset: 1, color: 'rgba(255, 129, 96, 0.08)' }
          ]
        }
      };
      const baseSeries = {
        name: '温度',
        type: 'line',
        smooth: true,
        data: temperatures,
        connectNulls: true,
        itemStyle: {
          color: '#43C8FF'
        },
        lineStyle: {
          color: '#43C8FF',
          width: 2
        },
        areaStyle: beforeAreaStyle,
        symbol: 'circle',
        symbolSize: 6
      };
      if (transportMarkLine) {
        baseSeries.markLine = transportMarkLine;
      }
      let series = [baseSeries];
      if (transportIndex !== -1) {
        const beforeData = temperatures.map((val, idx) => (idx <= transportIndex ? val : null));
        const afterData = temperatures.map((val, idx) => (idx >= transportIndex ? val : null));
        const beforeSeries = {
          name: '转运前',
          type: 'line',
          smooth: true,
          data: beforeData,
          connectNulls: true,
          itemStyle: {
            color: '#43C8FF'
          },
          lineStyle: {
            color: '#43C8FF',
            width: 2
          },
          areaStyle: beforeAreaStyle,
          symbol: 'circle',
          symbolSize: 6
        };
        if (transportMarkLine) {
          beforeSeries.markLine = transportMarkLine;
        }
        const afterSeries = {
          name: '转运后',
          type: 'line',
          smooth: true,
          data: afterData,
          connectNulls: true,
          itemStyle: {
            color: '#FF8160'
          },
          lineStyle: {
            color: '#FF8160',
            width: 2
          },
          areaStyle: afterAreaStyle,
          symbol: 'circle',
          symbolSize: 6
        };
        series = [beforeSeries, afterSeries];
      }
      const option = {
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          },
          formatter(params) {
            const axisValue = params && params[0] ? params[0].axisValue : '';
            const validParam = Array.isArray(params)
              ? params.find(item => item && item.value !== null && item.value !== undefined && item.value !== '')
              : null;
            const valueText = validParam ? `${validParam.value}°C` : '--';
            return `${axisValue}<br/>温度: ${valueText}`;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: times,
          axisLabel: {
            color: '#C3E4FF',
            rotate: 45,
            formatter(value) {
              if (value && value.indexOf(' ') > -1) {
                const parts = value.split(' ');
                if (parts.length >= 2) {
                  const datePart = parts[0];
                  const timePart = parts[1];
                  const dateParts = datePart.split('-');
                  if (dateParts.length >= 3) {
                    return `${dateParts[1]}-${dateParts[2]} ${timePart.substring(0, 5)}`;
                  }
                }
              }
              return value;
            }
          },
          axisLine: {
            lineStyle: {
              color: '#5596DF'
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '温度(°C)',
          nameTextStyle: {
            color: '#C3E4FF'
          },
          axisLabel: {
            color: '#C3E4FF',
            formatter: '{value}°C'
          },
          axisLine: {
            lineStyle: {
              color: '#5596DF'
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(85, 150, 223, 0.2)',
              type: 'dashed'
            }
          }
        },
        series
      };
      this.traceTemperatureChart.setOption(option);
      window.addEventListener('resize', this.handleTraceChartResize);
    },
    handleTraceChartResize() {
      if (this.traceTemperatureChart) {
        this.traceTemperatureChart.resize();
      }
    },
    disposeTraceChart() {
      if (this.traceTemperatureChart) {
        window.removeEventListener('resize', this.handleTraceChartResize);
        this.traceTemperatureChart.dispose();
        this.traceTemperatureChart = null;
      }
      this.traceTransportTime = '';
    },
    generateStaticTemperatureData() {
      // Generate random temperatures with smaller fluctuations (between -39.5 and -38.5)
      const generateRandomTemp = () => (Math.random() * 1 - 39.5).toFixed(1);
      
      // Create timestamps for x-axis with half-hour intervals (48 points for 24 hours)
      const xAxisData = [];
      const now = new Date();
      for (let i = 8; i >= 0; i--) {
        const time = new Date(now);
        time.setMinutes(now.getMinutes() - i * 30); // Half-hour intervals
        xAxisData.push(time.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }));
      }
      
      // Generate data for all four cabin temperatures
      this.lineData = [1, 2, 3, 4].map(index => {
        // Generate primary data with smaller fluctuations
        const data = xAxisData.map(() => generateRandomTemp());
        // Smaller bounds for less fluctuation (±0.1 instead of ±0.3)
        const data1 = data.map(val => (parseFloat(val) + 0.1).toFixed(1)); // Upper bound
        const data2 = data.map(val => (parseFloat(val) - 0.1).toFixed(1)); // Lower bound
        
        return {
          name: `舱温${index}`,
          id: index,
          data: data,
          xAxisData: xAxisData,
          data1: data1,
          data2: data2,
          max: -37.4, // Adjusted fixed max value
          min: -40.6, // Adjusted fixed min value
        };
      });
    },
    startPolling() {
      this.intervalId = setInterval(() => {
        // this.getlist();
      }, 60000); // 每60秒（1分钟）调用一次getlist
    },
    addAlarm(message, value, type, time) {
      this.alertYuanList.push({
        message,
        value,
        type,
        time,
      });
    },
    getCurrentTime() {
      const now = new Date();
      return `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()} ${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;
    },

    handleLinkShebei(type, item, index) {
      if (type == "water") {
        this.selectid = 1
      } else if (type == "meteorological") {
        this.selectid = 2
      } else if (type == "monitoring") {
        this.selectid = 1
      }
      if (type !== "monitoring") {
        // 查找对应的坐标
        // console.log("item", item);
        if (item.ACQUISITION_TIME) {
          this.currentTime = item.ACQUISITION_TIME.replace('T', ' ');
        }
        this.selectEquipment(item, 1)
        const selectedCoordinate = this.zuobiaolist.find(coord =>
          coord.toString() === item.EQUIPMENT_LOCATION
        );

        if (selectedCoordinate) {
          // 如果找到对应的坐标，将地图中心设置为该坐标
          this.map.setCenter(selectedCoordinate);

          // 可选：调整缩放级别
          this.map.setZoom(18);

          // 可选：添加动画效果
          this.map.panTo(selectedCoordinate);
        }

        // 更新 miaoshu 数据
        this.miaoshu = item;
        this.miaoshu.state = item.STATE == 0 ? "停止" : "正常";
        this.miaoshu.type = type == "water" ? 1 : 2;
        // // 调用 addEquipment 方法（如果需要的话）
        //   this.addEquipment(type == "water" ? 0 : 1);
        // 在这里处理点击事件
        this.getshebeidata(item);
      }
      else{
        if (index % 2 == 0) {
          this.initPlayer(item.video_address, item.serial_number);
        }
        else {
          this.initPlayer1(item.video_address, item.serial_number);
        }

        if (item.camera_location) {
          const position = item.camera_location.split(',');
          if (position) {
            // 设置地图中心点
            this.map.setCenter(position);
            this.map.setZoom(1);
            this.map.panTo(position);
          }
          // 不直接播放视频，等待用户点击地图上的标记
          return;
        }
      }

      // 您可以在这里添加您原来在 linkshebei 方法中的逻辑
    },
    getshebeidata(item) {
      select_equipmentv2({
        base_id: this.$route.query.base_id,
        equipmentID: item.ID
      }).then(res => {
      //   const data = res.data.shuju
      //   this.lineData = []

      //   this.lineData = [
      //     {
      //       name: "舱温一",
      //       id: 1,
      //       data: data.templist[0].y[0].data,
      //       xAxisData: data.templist[0].x,
      //       data1: data.templist[0].y[1].data,
      //       data2: data.templist[0].y[2].data,
      //       max: data.templist[0].max,
      //       min: data.templist[0].min,
      //     }
      //   ]  
      //   if (this.selectid == 1) {
      //     this.lineData.push(
      //       {
      //         name: "PH",
      //         id: 2,
      //         data: data.templist[2].y[0].data,
      //         xAxisData: data.templist[0].x,
      //         data1: data.templist[2].y[1].data,
      //         data2: data.templist[2].y[2].data,
      //         max: data.templist[2].max,
      //         min: data.templist[2].min,
      //       }, {
      //       name: "溶氧值",
      //       id: 3,
      //       data: data.templist[1].y[0].data,
      //       xAxisData: data.templist[0].x,
      //       data1: data.templist[1].y[1].data,
      //       data2: data.templist[1].y[2].data,
      //       max: data.templist[1].max,
      //       min: data.templist[1].min,
      //     }
      //     )
      //   }
      //   else if (this.selectid == 2) {
      //     if (data.templist && data.templist.length > 0){
      //       this.lineData.push(
      //       {
      //         name: "溶氧值",
      //         id: 2,
      //         data: data.templist[3].y[0].data,
      //         xAxisData: data.templist[0].x,
      //         data1: data.templist[3].y[1].data,
      //         data2: data.templist[3].y[2].data,
      //         max: data.templist[3].max,
      //         min: data.templist[3].min,
      //       }, {
      //       name: "PH",
      //       id: 3,
      //       data: data.templist[4].y[0].data,
      //       xAxisData: data.templist[0].x,
      //       data1: data.templist[4].y[1].data,
      //       data2: data.templist[4].y[2].data,
      //       max: data.templist[4].max,
      //       min: data.templist[4].min,
      //     }, {
      //       name: "雨量",
      //       id: 4,
      //       data: data.templist[5].y[0].data,
      //       xAxisData: data.templist[0].x,
      //       data1: data.templist[5].y[1].data,
      //       data2: data.templist[5].y[2].data,
      //       max: data.templist[5].max,
      //       min: data.templist[5].min,
      //     })}
      //     else {
      //   // 如果数据为空，重置 selectid 为 1
      //   this.selectid = 1;
      //   this.lineData = []; // 清空数据
      //   }
      //   }
      // })
      if (this.selectid == 1) {
        // Keep all four cabin temperatures for water quality devices
        // No need to slice, ensure all four are visible
        this.lineData.forEach((lineItem, index) => {
          // Make sure all four cabin temperature charts maintain their data and properties
          if (index < 4) {
            // Ensure each cabin temperature chart keeps its name, id, and other properties
            this.lineData[index] = {
              ...this.lineData[index],
              name: `舱温${index + 1}`,
              id: index + 1
            };
          }
        });
      }
      else if (this.selectid == 2) {
        // For meteorological devices, prepare the additional charts after the temperature
        const additionalCharts = [
          {
            name: "溶氧值",
            id: 5,
            data: res.data.shuju.templist[3].y[0].data,
            xAxisData: this.lineData[0].xAxisData, // Use our static x-axis data
            data1: res.data.shuju.templist[3].y[1].data,
            data2: res.data.shuju.templist[3].y[2].data,
            max: res.data.shuju.templist[3].max,
            min: res.data.shuju.templist[3].min,
          }, 
          {
            name: "PH",
            id: 6,
            data: res.data.shuju.templist[4].y[0].data,
            xAxisData: this.lineData[0].xAxisData, // Use our static x-axis data
            data1: res.data.shuju.templist[4].y[1].data,
            data2: res.data.shuju.templist[4].y[2].data,
            max: res.data.shuju.templist[4].max,
            min: res.data.shuju.templist[4].min,
          }
        ];
        
        // Make sure to preserve all four cabin temperature charts first
        // Then append the additional charts
        this.lineData = [...this.lineData.slice(0, 4), ...additionalCharts];
      }
    })
    },
    getlist() {
      this.base_id = this.$route.query.base_id
      shebeilistv2({
        base_id: this.base_id,
      }).then(res => {
        console.log('数据接口:', res);
        this.getshebeidata(res.data.shebeilist[0]);
        console.log("res",res);
        // let tianqi = res.data.tianqi;
        // Object.keys(tianqi).forEach(key => {
        //   if (Object.prototype.hasOwnProperty.call(this.wetherinfo, key)) {
        //     this.wetherinfo[key].value = parseFloat(parseFloat(tianqi[key]).toFixed(1));
        //   }
        // });
        this.shelist = res.data.shebeilist;
        this.shelist.map(item => {
          item.UANDL = JSON.parse(item.UANDL)
          if (item.EQUIPMENT_TYPE == '水质检测') {
            this.shebeilist.water.push(item)
          } else if (item.EQUIPMENT_TYPE == '气象检测') {
            this.shebeilist.meteorological.push(item)
          } else if (item.EQUIPMENT_TYPE == '监控检测') {
            this.shebeilist.monitoring.push(item)
          }
        })
        for (let i = 1; i < this.shelist.length; i++) {
          const device = this.shelist[i];
          const Online_Voltage = device.Online_Voltage;
          // 检查设备类型是否为水质设备
          if (device.EQUIPMENT_TYPE === '水质检测') {
            const oxygenLevel = device.O2;
            const temperature = device.TEM;
            const pHValue = device.PH;
            const UANDL = device.UANDL;
            const time = device.ACQUISITION_TIME;

            let parsedUANDL = UANDL;
            if (typeof UANDL === 'string') {
              try {
                parsedUANDL = JSON.parse(UANDL);
              } catch (error) {
                console.error('解析 UANDL 失败:', error);
              }
            } else if (typeof UANDL !== 'object' || UANDL === null) {
              console.error('UANDL 不是有效的对象或 JSON 字符串');
              return; // 或者进行其他错误处理
            }
            if (oxygenLevel < parsedUANDL.o2.th[0] || oxygenLevel > parsedUANDL.o2.th[1]) {
              const alarmMessage = `${device.EQUIPMENT_NAME}的溶氧值异常`;
              const value = oxygenLevel
              this.addAlarm(alarmMessage, value, 1, time);
            }
            if (temperature < parsedUANDL.te.th[0] || temperature > parsedUANDL.te.th[1]) {
              const alarmMessage = `${device.EQUIPMENT_NAME}的温度异常`;
              const value = temperature
              this.addAlarm(alarmMessage, value, 1, time);
            }

            if (pHValue < parsedUANDL.ph.th[0] || pHValue > parsedUANDL.ph.th[1]) {
              const alarmMessage = `${device.EQUIPMENT_NAME}的PH值异常`;
              const value = pHValue
              this.addAlarm(alarmMessage, value, 1, time);
            }
            if (Online_Voltage == 0 || Online_Voltage < 10) {
              const alarmMessage = `${device.EQUIPMENT_NAME}的电压值异常`;
              const value = Online_Voltage
              this.addAlarm(alarmMessage, value, 2, time);
            }
          }
        }
        this.zuobiaolist = res.data.zuobiaoilist;
        this.inforlist = res.data.inforlist;
        this.alertlist = res.data.alertlist;
        // this.tianqi = res.data.tianqi;
        this.chuangan2 = res.data.chuangan2; //所有设备的传感器参数（最新的一条）
        this.chuangan = res.data.chuangan;  //传感器传来的设备一参数,用来初始化

        // this.PH = res.data.shebeilist[0].PH
        // this.TEM = res.data.shebeilist[0].TEM //初始温度
        // this.O2 = res.data.shebeilist[0].O2
        // this.SALT = res.data.shebeilist[0].SALT
        // this.CON = res.data.shebeilist[0].CON

        // this.shebeiname="设备参数  " +  this.chuangan.EQUIPMENT_NAME

        // this.shuju = res.data.shuju;
        this.shuju2 = res.data.shuju2;
        this.aa = this.shuju2.templist[0];//默认折线图、设备一参数 
        this.renderMap();
        this.handleLinkShebei('water', { ID: 1 })
        this.selectEquipment(this.shelist[0], 1) //默认选择第一个设备展示
      })
    },
    selectEquipment(i, index) {
      if (i.ACQUISITION_TIME) {
        this.currentTime = i.ACQUISITION_TIME.replace('T', ' ');
      }
      this.equipmentID = i.ID
      if (i.EQUIPMENT_TYPE == '水质检测') {
        this.weatherData = false;
        this.waterData = true;
        this.shebeiname = "设备参数  " + i.EQUIPMENT_NAME;
        this.PH = i.PH
        this.TEM = i.TEM
        this.O2 = i.O2
        this.SALT = i.SALT
        this.CON = i.CON
        this.aa = ''
      } else if (i.EQUIPMENT_TYPE == '气象检测') {
        this.weatherData = true;
        this.waterData = false;
        this.shebeiname = "设备参数  " + i.EQUIPMENT_NAME;
        this.HUMIDITY = i.HUMIDITY
        this.TEM = i.TEM
        this.RAINFALL = i.RAINFALL
        this.ATM = i.ATM
        this.aa = ''
      }
      //  点击设备设置中心位置
      for (this.zuoBiaoProp of this.zuobiaolist) {
        this.X = this.zuoBiaoProp[0];
        this.Y = this.zuoBiaoProp[1];
        const zuoBiaoStr = this.zuoBiaoProp.toString();
        if (zuoBiaoStr == i.EQUIPMENT_LOCATION) {
          this.map.setCenter([this.zuoBiaoProp[0], this.zuoBiaoProp[1]]);
        }
      }
    },
    addEquipment(ty) {
      console.log("this.equipmentID", this.equipmentID);
      select_equipmentv2({
        base_id: this.$route.query.base_id,
        equipmentID: this.equipmentID
      }).then(res => {
        this.shuju = res.data.shuju;
        this.aa = this.shuju.templist[this.active];
      })
    },
    renderMap() {
      this.$AMapLoader.load({
        key: 'bb41d02b6376f70646e2490b6bf5f80b',
        version: '1.4.15',
        plugins: ['AMap.MapType'], // 添加 MapType 插件
        AMapUI: {
          version: '1.1',
          plugins: []
        },
        Loca: {
          version: '1.3.2'
        }
      }).then((AMap) => {
        this.map = new AMap.Map('map-container', {
          layers: [new AMap.TileLayer.Satellite(), new AMap.TileLayer.RoadNet()],
          zoom: 3, // 初始缩放级别
          center: [-118.69542132875415, -10.41638743134329] // 设置初始地图中心为上海
        });
        
        // 添加地图类型切换控件
        this.map.addControl(new AMap.MapType({
          defaultType: 1 // 0代表默认地图，1代表卫星地图
        }));

        // 静态设备标记
        const staticMarkers = [
          {
            position: [-150.69542132875415, 13.41638743134329], // 设备坐标
            name: '宁泰冷1', // 设备名称
            location: '上海市浦东新区', // 设备位置
            type: 'transport'
          },
          {
            position: [-160.69542132875415, 5.41638743134329], // 设备坐标
            name: '宁泰冷2', // 设备名称
            location: '上海市黄浦区', // 设备位置
            type: 'transport'
          },
          {
            position: [-190.69542132875415, 15.41638743134329], // 设备坐标
            name: '宁泰冷3', // 设备名称
            location: '上海市浦东新区' ,// 设备位置
            type: 'transport'
          },
          {
            position: [-210.69542132875415, 25.41638743134329], // 设备坐标
            name: '宁泰冷4', // 设备名称
            location: '上海市黄浦区', // 设备位置
            type: 'transport'
          },
          {
            position: [-118.69542132875415, -10.41638743134329], // 设备坐标
            name: '宁泰1', // 设备名称
            location: '上海市黄浦区' ,// 设备位置
            type: 'fishing'
          },
          {
            position: [-110.99542132875415, -5.41638743134329], // 设备坐标
            name: '宁泰2', // 设备名称
            location: '上海市黄浦区' ,// 设备位置
            type: 'fishing'
          },
          {
            position: [-109.99542132875415, 2.41638743134329], // 设备坐标
            name: '宁泰3', // 设备名称
            location: '上海市黄浦区' ,// 设备位置
            type: 'fishing'
          },
          {
            position: [-109.99542132875415, -16.41638743134329], // 设备坐标
            name: '宁泰4', // 设备名称
            location: '上海市黄浦区' ,// 设备位置
            type: 'fishing'
          },
          {
            position: [-90.99542132875415, -16.41638743134329], // 设备坐标
            name: '宁泰5', // 设备名称
            location: '上海市黄浦区' ,// 设备位置
            type: 'fishing'
          },
          {
            position: [-90.99542132875415, -23.41638743134329], // 设备坐标
            name: '宁泰6', // 设备名称
            location: '上海市黄浦区' ,// 设备位置
            type: 'fishing'
          },
          // 添加更多静态设备
        ];

        staticMarkers.forEach((markerInfo) => {
          const marker = new AMap.Marker({
            position: markerInfo.position,
            offset: new AMap.Pixel(-20, -25), // 偏移值
            icon: new AMap.Icon({
              size: new AMap.Size(40, 40), // 图标尺寸
              image: require('@/assets/ui/device-icon-o2.png'), // Icon的图像
              imageSize: new AMap.Size(40, 40) // 根据所设置的大小拉伸或压缩图片
            }),
            label: {
              content: `<div class="custom-label" style="padding: 10px; margin:0px 0 0 40px">${markerInfo.name}</div>`,
            },
          });

          marker.on('click', () => {
            this.box = 1;
            this.map.setCenter(markerInfo.position);
            this.miaoshu = {
              EQUIPMENT_NAME: markerInfo.name,
              EQUIPMENT_LOCATION: markerInfo.location
            };
          });

          this.map.add(marker);
        });

        // 根据设备数量和位置调整地图中心和缩放级别
        if (staticMarkers.length > 0) {
          const bounds = new AMap.Bounds();
          staticMarkers.forEach(markerInfo => {
            bounds.extend(markerInfo.position);
          });
          this.map.setBounds(bounds, true, [40, 40, 40, 40]); // 设置地图边界和内边距
        }
      });
    },
    async getEquipmentType(local, base_id) {
      let type = '水质检测' // 默认类型
      await caicon({ zuobiao: local, base_id: base_id }).then(res => {
        if (res && res.data) {
          type = res.data
        }
      })
      return type
    },

    setCustomLabelStyle(marker, equipmentType, index) {
      // 使用 setTimeout 来确保 DOM 已经更新
      console.log("labelDom", marker, equipmentType, index);
      const findLabel = () => {
        const labelDom = document.querySelector(`.amap-marker-label .custom-label-${index}`);
        if (labelDom) {

          // labelDom.classList.remove('water-quality-label', 'meteorological-label');
          if (equipmentType === '水质检测') {
            labelDom.classList.add('water-quality-label');
          } else if (equipmentType === '气象检测') {
            labelDom.classList.add('meteorological-label');
          }
          return true;
        }
        return false;
      };

      // 如果直接查找失败，则开始轮询
      if (!findLabel()) {
        let attempts = 0;
        const interval = setInterval(() => {
          if (findLabel() || attempts >= 10) {
            clearInterval(interval);
          }
          attempts++;
        }, 300);
      }
    },
    onCloseCover() {
      this.box = 0;
    },
    initPlayer(url, SerialNumber) {
      if (!SerialNumber || !this.jktokens.value) {
        console.error('设备序列号或访问令牌未设置');
        return;
      }
      this.player = new EZUIKit.EZUIKitPlayer({
        id: 'video-container',
        accessToken: this.jktokens.value,
        url: url,
        height: '220',
        width: '450',
        template: 'e33cecdfc3bb4019a06591a15cda2b1f',
        autoplay: true,  // 自动播放
        footer: ['fullScreen'], 
        handleError: (e) => {  // 添加错误处理
          console.error('播放器错误:', e);
        }
      });
    },
    initPlayer1(url, SerialNumber) {
      if (!SerialNumber || !this.jktokens.value) {
        console.error('设备序列号或访问令牌未设置');
        return;
      }
      this.player1 = new EZUIKit.EZUIKitPlayer({
        id: 'video-container1',
        accessToken: this.jktokens.value,
        url: url,
        height: '220',
        width: '450',
        template: 'e33cecdfc3bb4019a06591a15cda2b1f',
        autoplay: true,  // 自动播放
        handleError: (e) => {  // 添加错误处理
          console.error('播放器错误:', e);
        },
        // header: ['capturePicture', 'save', 'zoom'],  
        // footer: ['hd', 'fullScreen']  
      });
    },
    GetCamera() {
      this.base_id = this.$route.query.base_id
      getcamera({
        base_id: this.base_id,
      }).then(res => {
        this.cameralist = res.item_list;
        const videoAddresses = this.cameralist.map(camera => camera.video_address);
        const SerialNumber = this.cameralist.map(camera => camera.serial_number);
        this.videoAddresses = videoAddresses;
        this.SerialNumber = SerialNumber;
        console.log('视频地址数组:', res);
        if (this.cameralist.length > 0) {
          this.shebeilist.monitoring = this.cameralist;
        }

        // this.initPlayer(this.cameralist[0].video_address, this.SerialNumber[0]);
        // this.initPlayer1(this.cameralist[1].video_address, this.SerialNumber[1]);
      })

    },
    async getToken() {
      try {
        const appKey = '3d0be5dc16b846e58ba2e4efb80d6d7f'; // 替换为你的appKey  
        const appSecret = '1d040ec6b1a4d12061fa97ef21987942'; // 替换为你的appSecret  

        const response = await axios.post('https://open.ys7.com/api/lapp/token/get',
          `appKey=${appKey}&appSecret=${appSecret}`,
          {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          }
        );
        // 处理响应数据  
        this.jktokens.value = response.data.data.accessToken;
        console.log('shuju:', response.data.data.accessToken); // 这里你应该会看到返回的token数据（如果请求成功的话）  
        //  this.jktokens=response.data.accessToken;
      } catch (error) {
        // 错误处理  
        console.error('获取Token失败:', error);
      }
    },
   GetWeather () {
      // 获取 base_id 参数（如果有的话，可以根据需求传入）
      getweather({
        city: this.city,
      }).then(res => {
        this.livetianqi = {
        temperature: res.temperature,  // 温度
        humidity: res.humidity,        // 湿度
        wind_direction: res.wind_direction, // 风向
        wind_power: res.wind_power,     // 风力    
        guangzhao: res.guangzhao, //光照
        precipitation: res.precipitation,   // 降水量
        pressure: res.pressure ,       // 气压
         };
         Object.keys(this.livetianqi).forEach(key => {
          if (Object.prototype.hasOwnProperty.call(this.wetherinfo1, key)) {
            this.wetherinfo1[key].value = this.livetianqi[key];  // 更新value字段
          }
        });
        console.log(this.wetherinfo1);
       })
       .catch(error => {
          // 处理错误并显示错误消息
          console.error('获取天气数据失败:', error);
          this.errorMessage = '获取天气数据失败，请稍后再试。';  // 清除已有的天气数据
        });
    },
    startFisheryAutoScroll() {
      const scrollContainer = this.$el.querySelector('.fishery-list-wrapper');
      if (!scrollContainer) return;

      // 设置滚动速度（每30毫秒滚动1.5像素，更平滑）
      const scrollSpeed = 1.5;
      const scrollInterval = 30;

      this.scrollTimer = setInterval(() => {
        if (scrollContainer) {
          // 获取当前滚动位置
          const currentScroll = scrollContainer.scrollTop;
          // 获取最大滚动高度
          const maxScroll = scrollContainer.scrollHeight - scrollContainer.clientHeight;

          if (maxScroll <= 0) {
            // 如果内容不足以滚动，则重置
            scrollContainer.scrollTop = 0;
            this.scrollPosition = 0;
          } else if (currentScroll >= maxScroll - 1) {
            // 滚动到底部时，平滑回到顶部（使用requestAnimationFrame实现无缝循环）
            scrollContainer.scrollTop = 0;
            this.scrollPosition = 0;
          } else {
            // 继续向下滚动
            this.scrollPosition += scrollSpeed;
            scrollContainer.scrollTop = this.scrollPosition;
          }
        }
      }, scrollInterval);
    },
    // 初始化捕捞量mock数据
    initCatchVolumeData() {
      const defaultFisheries = ['东海渔场', '黄海渔场', '南海渔场', '舟山渔场'];
      const fisheryNames = (this.fisheryList && this.fisheryList.length >= 4)
        ? this.fisheryList.slice(0, 4).map(item => item.name)
        : defaultFisheries;

      const generateFisheryData = (min, max) => fisheryNames.map(name => ({
        name,
        value: Math.floor(Math.random() * (max - min + 1) + min)
      }));

      // 近一周：捕捞量 80-200 吨
      this.catchVolumeData.week = generateFisheryData(80, 200);

      // 近一月：捕捞量 400-900 吨
      this.catchVolumeData.month = generateFisheryData(400, 900);

      // 近一年：捕捞量 3000-8000 吨
      this.catchVolumeData.year = generateFisheryData(3000, 8000);
    },
    // 初始化捕捞量图表
    initCatchVolumeChart() {
      this.$nextTick(() => {
        const chartDom = this.$el.querySelector('#catch-volume-chart');
        if (!chartDom) return;

        this.catchVolumeChart = echarts.init(chartDom);
        this.updateCatchVolumeChart();
        
        // 监听窗口大小变化
        this.chartResizeHandler = () => {
          if (this.catchVolumeChart) {
            this.catchVolumeChart.resize();
          }
        };
        window.addEventListener('resize', this.chartResizeHandler);
      });
    },
    // 更新捕捞量图表
    updateCatchVolumeChart() {
      if (!this.catchVolumeChart) return;

      const currentData = this.catchVolumeData[this.catchVolumeTimeRange] || [];
      const categories = currentData.map(item => item.name);
      const values = currentData.map(item => item.value);
      const option = {
        tooltip: {
          trigger: 'item',
          backgroundColor: 'rgba(0, 0, 0, 0.7)',
          borderColor: 'rgba(108, 140, 188, 0.8)',
          borderWidth: 1,
          textStyle: {
            color: '#fff'
          },
          formatter: params => `${params.name}<br/>捕捞量：${params.value} 吨`
        },
        grid: {
          left: '10%',
          right: '10%',
          top: '20%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: categories,
          axisLine: {
            lineStyle: {
              color: 'rgba(108, 140, 188, 0.5)'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#6C8CBC',
            fontSize: 12,
            interval: 0
          }
        },
        yAxis: {
          type: 'value',
          name: '捕捞量（吨）',
          nameTextStyle: {
            color: '#6C8CBC',
            fontSize: 12
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: 'rgba(108, 140, 188, 0.2)',
              type: 'dashed'
            }
          },
          axisLabel: {
            color: '#6C8CBC',
            fontSize: 12
          }
        },
        series: [
          {
            name: '捕捞量',
            type: 'bar',
            data: values,
            barWidth: '40%',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#5CA0B1' },
                { offset: 1, color: '#99BB6D' }
              ]),
              borderRadius: [4, 4, 0, 0]
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#6CB8C9' },
                  { offset: 1, color: '#A9CB7D' }
                ])
              }
            },
            label: {
              show: true,
              position: 'top',
              color: '#FFFFFF',
              fontSize: 11,
              formatter: '{c} 吨'
            }
          }
        ]
      };

      this.catchVolumeChart.setOption(option, true);
    },
    // 切换时间范围
    changeTimeRange(range) {
      this.catchVolumeTimeRange = range;
      if (range === 'custom') {
        // 如果切换到自定义,需要等待用户选择日期
        return;
      }
      this.updateCatchVolumeChart();
    },
    // 生成自定义日期范围的捕捞量数据
    generateCustomCatchVolumeData() {
      if (!this.catchVolumeCustomDateRange.startDate || !this.catchVolumeCustomDateRange.endDate) {
        return;
      }
      const startDate = new Date(this.catchVolumeCustomDateRange.startDate);
      const endDate = new Date(this.catchVolumeCustomDateRange.endDate);
      const daysDiff = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24)) + 1;
      
      const defaultFisheries = ['东海渔场', '黄海渔场', '南海渔场', '舟山渔场'];
      const fisheryNames = (this.fisheryList && this.fisheryList.length >= 4)
        ? this.fisheryList.slice(0, 4).map(item => item.name)
        : defaultFisheries;

      // 根据天数范围生成随机数据
      const min = Math.max(50, daysDiff * 10);
      const max = Math.min(10000, daysDiff * 200);
      
      this.catchVolumeData.custom = fisheryNames.map(name => ({
        name,
        value: Math.floor(Math.random() * (max - min + 1) + min)
      }));
      
      this.updateCatchVolumeChart();
    },
    // 初始化分级捕捞量mock数据
    initGradedCatchData() {
      const levels = ['大', '中', '小']; // 等级：大中小三级
      
      // 生成近一周数据（7条）
      this.gradedCatchData.week = [];
      for (let i = 0; i < 7; i++) {
        const randomLevel = levels[Math.floor(Math.random() * levels.length)];
        const randomCatch = Math.floor(Math.random() * 500 + 100); // 随机捕捞量 100-600
        this.gradedCatchData.week.push({
          等级: randomLevel,
          捕捞量: randomCatch
        });
      }
      
      // 生成近一月数据（30条）
      this.gradedCatchData.month = [];
      for (let i = 0; i < 30; i++) {
        const randomLevel = levels[Math.floor(Math.random() * levels.length)];
        const randomCatch = Math.floor(Math.random() * 800 + 150); // 随机捕捞量 150-950
        this.gradedCatchData.month.push({
          等级: randomLevel,
          捕捞量: randomCatch
        });
      }
      
      // 生成近一年数据（12条）
      this.gradedCatchData.year = [];
      for (let i = 0; i < 12; i++) {
        const randomLevel = levels[Math.floor(Math.random() * levels.length)];
        const randomCatch = Math.floor(Math.random() * 5000 + 1000); // 随机捕捞量 1000-6000
        this.gradedCatchData.year.push({
          等级: randomLevel,
          捕捞量: randomCatch
        });
      }
      
      console.log('分级捕捞量数据已初始化:', this.gradedCatchData);
    },
    // 初始化分级捕捞量饼状图
    initGradedCatchChart() {
      this.$nextTick(() => {
        const chartDom = this.$el.querySelector('#graded-catch-chart');
        if (!chartDom) return;

        this.gradedCatchChart = echarts.init(chartDom);
        this.updateGradedCatchChart();
        
        // 监听窗口大小变化
        this.gradedCatchChartResizeHandler = () => {
          if (this.gradedCatchChart) {
            this.gradedCatchChart.resize();
          }
        };
        window.addEventListener('resize', this.gradedCatchChartResizeHandler);
      });
    },
    // 更新分级捕捞量饼状图
    updateGradedCatchChart() {
      if (!this.gradedCatchChart) return;

      // 获取当前时间范围的数据
      const currentData = this.gradedCatchData[this.gradedCatchTimeRange];
      
      // 按等级统计捕捞量
      const stats = {
        '大': 0,
        '中': 0,
        '小': 0
      };
      
      currentData.forEach(item => {
        if (Object.prototype.hasOwnProperty.call(stats, item.等级)) {
          stats[item.等级] += item.捕捞量;
        }
      });

      // 转换为饼状图数据格式
      const pieData = [
        { value: stats['大'], name: '大', itemStyle: { color: '#5CA0B1' } },
        { value: stats['中'], name: '中', itemStyle: { color: '#99BB6D' } },
        { value: stats['小'], name: '小', itemStyle: { color: '#6C8CBC' } }
      ];

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c}吨 ({d}%)',
          backgroundColor: 'rgba(0, 0, 0, 0.7)',
          borderColor: 'rgba(108, 140, 188, 0.8)',
          borderWidth: 1,
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          show: false // 不显示图例，因为我们在模板中自定义了
        },
        series: [
          {
            name: '分级捕捞量',
            type: 'pie',
            radius: ['40%', '70%'], // 环形图
            center: ['50%', '55%'], // 稍微向下偏移，为上方控件留空间
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 4,
              borderColor: 'rgba(0, 0, 0, 0.3)',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}\n{c}吨',
              color: '#FFFFFF',
              fontSize: 12,
              fontWeight: 'bold'
            },
            labelLine: {
              show: true,
              length: 15,
              length2: 10,
              lineStyle: {
                color: '#6C8CBC'
              }
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 14,
                fontWeight: 'bold'
              },
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            data: pieData
          }
        ]
      };

      this.gradedCatchChart.setOption(option, true);
    },
    // 切换分级捕捞量时间范围
    changeGradedCatchTimeRange(range) {
      this.gradedCatchTimeRange = range;
      if (range === 'custom') {
        // 如果切换到自定义,需要等待用户选择日期
        return;
      }
      this.updateGradedCatchChart();
    },
    // 生成自定义日期范围的分级捕捞量数据
    generateCustomGradedCatchData() {
      if (!this.gradedCatchCustomDateRange.startDate || !this.gradedCatchCustomDateRange.endDate) {
        return;
      }
      const startDate = new Date(this.gradedCatchCustomDateRange.startDate);
      const endDate = new Date(this.gradedCatchCustomDateRange.endDate);
      const daysDiff = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24)) + 1;
      
      const levels = ['大', '中', '小'];
      const dataCount = Math.min(daysDiff, 100); // 最多100条数据
      
      this.gradedCatchData.custom = [];
      for (let i = 0; i < dataCount; i++) {
        const randomLevel = levels[Math.floor(Math.random() * levels.length)];
        const randomCatch = Math.floor(Math.random() * 1000 + 100);
        this.gradedCatchData.custom.push({
          等级: randomLevel,
          捕捞量: randomCatch
        });
      }
      
      this.updateGradedCatchChart();
    },
    // 初始化捕捞量折线图mock数据
    initCatchLineData() {
      const now = new Date();
      
      // 生成近一周数据（每天）
      const weekDates = [];
      const weekData = [];
      for (let i = 6; i >= 0; i--) {
        const date = new Date(now);
        date.setDate(date.getDate() - i);
        weekDates.push((date.getMonth() + 1) + '/' + date.getDate());
        // 生成随机捕捞量（100-600吨）
        weekData.push(Math.floor(Math.random() * 500 + 100));
      }
      this.catchLineData.week = { dates: weekDates, data: weekData };

      // 生成近一个月数据（每天）
      const monthDates = [];
      const monthData = [];
      for (let i = 29; i >= 0; i--) {
        const date = new Date(now);
        date.setDate(date.getDate() - i);
        monthDates.push((date.getMonth() + 1) + '/' + date.getDate());
        // 生成随机捕捞量（150-950吨）
        monthData.push(Math.floor(Math.random() * 800 + 150));
      }
      this.catchLineData.month = { dates: monthDates, data: monthData };

      // 生成近一年数据（每月）
      const yearDates = [];
      const yearData = [];
      for (let i = 11; i >= 0; i--) {
        const date = new Date(now);
        date.setMonth(date.getMonth() - i);
        yearDates.push((date.getMonth() + 1) + '月');
        // 生成随机捕捞量（1000-6000吨）
        yearData.push(Math.floor(Math.random() * 5000 + 1000));
      }
      this.catchLineData.year = { dates: yearDates, data: yearData };
      
      console.log('捕捞量折线图数据已初始化:', this.catchLineData);
    },
    // 初始化捕捞量折线图
    initCatchLineChart() {
      this.$nextTick(() => {
        const chartDom = this.$el.querySelector('#catch-line-chart');
        if (!chartDom) return;

        this.catchLineChart = echarts.init(chartDom);
        this.updateCatchLineChart();
        
        // 监听窗口大小变化
        this.catchLineChartResizeHandler = () => {
          if (this.catchLineChart) {
            this.catchLineChart.resize();
          }
        };
        window.addEventListener('resize', this.catchLineChartResizeHandler);
      });
    },
    // 更新捕捞量折线图
    updateCatchLineChart() {
      if (!this.catchLineChart) return;

      const currentData = this.catchLineData[this.catchLineTimeRange];
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: 'rgba(0, 0, 0, 0.7)'
            }
          },
          backgroundColor: 'rgba(0, 0, 0, 0.7)',
          borderColor: 'rgba(108, 140, 188, 0.8)',
          borderWidth: 1,
          textStyle: {
            color: '#fff'
          }
        },
        grid: {
          left: '10%',
          right: '10%',
          top: '25%',
          bottom: '20%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: currentData.dates,
          axisLine: {
            lineStyle: {
              color: 'rgba(108, 140, 188, 0.5)'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#6C8CBC',
            fontSize: 11,
            rotate: this.catchLineTimeRange === 'year' ? 0 : (this.catchLineTimeRange === 'month' ? 45 : 0)
          }
        },
        yAxis: {
          type: 'value',
          name: '捕捞量（吨）',
          nameTextStyle: {
            color: '#6C8CBC',
            fontSize: 12
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: 'rgba(108, 140, 188, 0.2)',
              type: 'dashed'
            }
          },
          axisLabel: {
            color: '#6C8CBC',
            fontSize: 11
          }
        },
        series: [
          {
            name: '捕捞量',
            type: 'line',
            smooth: true,
            data: currentData.data,
            itemStyle: {
              color: '#5CA0B1'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(92, 160, 177, 0.3)' },
                { offset: 1, color: 'rgba(92, 160, 177, 0.05)' }
              ])
            },
            lineStyle: {
              width: 2,
              color: '#5CA0B1'
            },
            symbol: 'circle',
            symbolSize: 6,
            emphasis: {
              focus: 'series',
              itemStyle: {
                color: '#99BB6D',
                borderColor: '#5CA0B1',
                borderWidth: 2
              }
            },
            label: {
              show: false
            }
          }
        ]
      };

      this.catchLineChart.setOption(option, true);
    },
    // 切换捕捞量折线图时间范围
    changeCatchLineTimeRange(range) {
      this.catchLineTimeRange = range;
      if (range === 'custom') {
        // 如果切换到自定义,需要等待用户选择日期
        return;
      }
      this.updateCatchLineChart();
    },
    // 生成自定义日期范围的捕捞量折线图数据
    generateCustomCatchLineData() {
      if (!this.catchLineCustomDateRange.startDate || !this.catchLineCustomDateRange.endDate) {
        return;
      }
      const startDate = new Date(this.catchLineCustomDateRange.startDate);
      const endDate = new Date(this.catchLineCustomDateRange.endDate);
      const daysDiff = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24)) + 1;
      
      const dates = [];
      const data = [];
      
      // 如果时间范围小于等于30天,按天显示
      if (daysDiff <= 30) {
        for (let i = 0; i < daysDiff; i++) {
          const date = new Date(startDate);
          date.setDate(date.getDate() + i);
          dates.push((date.getMonth() + 1) + '/' + date.getDate());
          data.push(Math.floor(Math.random() * 500 + 100));
        }
      } else if (daysDiff <= 365) {
        // 如果时间范围在30-365天,按周显示
        const weeks = Math.ceil(daysDiff / 7);
        for (let i = 0; i < weeks; i++) {
          const date = new Date(startDate);
          date.setDate(date.getDate() + i * 7);
          dates.push((date.getMonth() + 1) + '/' + date.getDate());
          data.push(Math.floor(Math.random() * 3000 + 500));
        }
      } else {
        // 如果时间范围大于365天,按月显示
        const months = Math.ceil(daysDiff / 30);
        for (let i = 0; i < months; i++) {
          const date = new Date(startDate);
          date.setMonth(date.getMonth() + i);
          dates.push((date.getMonth() + 1) + '月');
          data.push(Math.floor(Math.random() * 5000 + 1000));
        }
      }
      
      this.catchLineData.custom = { dates, data };
      this.updateCatchLineChart();
    }

  }

}
</script>
<template>

  <div class="w-100 h-100 d-flex flex-column  ">

    <div class="w-100 h-100 map-container position-absolute " id="map-container"></div>
    <img src="@/assets/ui/bg.png" alt="" class="w-100 h-100 position-absolute top-0 left-0"
      style="pointer-events: none;">
    <el-dialog
      :visible.sync="showTraceDialog"
      :title="traceModalTitle"
      width="1200px"
      custom-class="trace-records-dialog"
      :close-on-click-modal="false"
      @close="onTraceDialogClose"
    >
      <div class="trace-records-container">
        <div v-if="traceRecordMeta" class="trace-record-meta">
          <div>捕捞船：{{ traceRecordMeta.record.ship_name }}</div>
          <div>捕捞时间：{{ traceRecordMeta.record.catch_time }}</div>
          <div>捕捞地点：{{ traceRecordMeta.record.location }}</div>
        </div>
        <el-table
          :data="traceRecordsTable"
          style="width: 100%"
          :header-cell-style="{ background: 'rgba(44, 81, 153, 0.6)', color: '#C3E4FF', border: '1px solid rgba(85, 150, 223, 0.3)' }"
          :row-style="{ background: 'rgba(10, 20, 40, 0.9)', color: '#C3E4FF' }"
          stripe
        >
          <el-table-column label="编号" width="80" align="center">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="RFID" label="RFID" width="160" show-overflow-tooltip></el-table-column>
          <el-table-column prop="grade" label="渔获等级" width="90">
            <template slot-scope="scope">
              <el-tag :type="scope.row.grade === '大' ? 'success' : scope.row.grade === '中' ? 'warning' : 'info'" size="small">
                {{ scope.row.grade }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="ship_name" label="捕捞船名" width="140"></el-table-column>
          <el-table-column prop="location" label="捕捞地点" width="220" show-overflow-tooltip></el-table-column>
          <el-table-column prop="catch_time" label="捕捞时间" width="200"></el-table-column>
          <el-table-column prop="transport_ship" label="转运船名" width="140"></el-table-column>
          <el-table-column prop="transport_time" label="转运时间" width="200"></el-table-column>
          <el-table-column prop="arrive_time" label="到港时间" width="200"></el-table-column>
          <el-table-column prop="port_name" label="港口名" width="140"></el-table-column>
          <el-table-column prop="details" label="详情" width="120" fixed="right">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="openTraceRecordDetail(scope.row)"
                style="color: #43C8FF; cursor: pointer;"
              >
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showTraceDialog = false">关闭</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="温度变化详情"
      :visible.sync="traceDetailDialog"
      width="800px"
      :close-on-click-modal="false"
      custom-class="trace-detail-dialog"
      @close="closeTraceDetailDialog"
    >
      <div class="trace-detail-content">
        <div v-if="traceTemperatureData && traceTemperatureData.length" class="trace-temperature-chart-container">
          <div class="chart-title">温度变化曲线</div>
          <div ref="traceTemperatureChart" class="trace-temperature-chart"></div>
        </div>
        <div v-else class="trace-detail-text">
          <el-input
            type="textarea"
            :rows="8"
            v-model="traceRecordDetail"
            placeholder="暂无详情内容"
            :readonly="true"
          ></el-input>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeTraceDetailDialog">关闭</el-button>
      </span>
    </el-dialog>
    <div v-if="box === 1" class="equip-box"
      :style="{ backgroundImage: `url(${backgroundImage})`, height: this.miaoshuFormatted.length > 12 ? '20rem' : '20rem' }">
      <!-- <img src="@/assets/ui/prompt.png" alt=""> -->
      <div class="text">
        <div class="info-table">
          <div v-for="(item, index) in miaoshuFormatted" :key="index"
            :class="['info-row', { 'full-width': index < 3 }]">
            <div class="info-label"><span :style="{ color: labelcolor }">{{ item.label }}</span></div>
            <div class="info-value"><span :style="{ color: valuecolor }">{{ item.value }}</span></div>
          </div>
        </div>
      </div>
      <div class="close-icon d-flex align-items-center justify-content-center" @click="onCloseCover">
        <svg t="1639825855503" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
          p-id="26567" width="1rem" height="1rem">
          <path
            d="M846.005097 957.24155c-28.587082 0-57.174164-10.911514-78.996169-32.733519L96.632851 254.131955c-43.644009-43.644009-43.644009-114.348328 0-157.992337s114.348328-43.644009 157.992337 0L925.001265 766.515694c43.644009 43.644009 43.644009 114.348328 0 157.992337C903.17926 946.330036 874.592179 957.24155 846.005097 957.24155z"
            p-id="26568" fill="#ffffff"></path>
          <path
            d="M175.62902 957.24155c-28.587082 0-57.174164-10.911514-78.996169-32.733519-43.644009-43.644009-43.644009-114.348328 0-157.992337L767.008928 96.139617c43.644009-43.644009 114.348328-43.644009 157.992337 0s43.644009 114.348328 0 157.992337L254.625188 924.508032C232.803183 946.330036 204.216101 957.24155 175.62902 957.24155z"
            p-id="26569" fill="#ffffff"></path>
        </svg>
      </div>
    </div>
    <div class="header">
      <Head2 :isShow="true" :trace-search-enabled="true" @trace-search="handleTraceSearch"></Head2>
    </div>
    <div class="main d-flex flex-row  ">
      <div class="home-sidebar  ">
        <div style="height: 64.8%;">
          <SubtitledSection title="船舶列表">
            <template>
              <DeviceList :shebeilist="shebeilist" @link-shebei="handleLinkShebei"></DeviceList>
            </template>
          </SubtitledSection>
        </div>
        <!-- <div style="height: 32.6%; ">
          <SubtitledSection title="报警信息">
            <template>
              <AlarmList :baselist="alertYuanList"></AlarmList>
            </template>
          </SubtitledSection>
        </div> -->

      </div>
      <div class="home-center">
        <!-- <div class="info-box">
          <div v-for="(item, i) in wetherinfo1" :key="i" class="info-item"
            :style="{ backgroundImage: 'url(' + require(`@/assets/ui/${item.img}`) + ')' }">
            <div style=" margin-left: 3.4rem;">
              {{ item.value }}
            </div>
          </div>
        </div> -->
        <div class="bottom-box ">
          <div style="width:49.5% ;">
            <SubtitledSectionLong title="渔场信息列表">
              <template>
                <div class="fishery-list-wrapper" ref="fisheryScrollContainer">
                  <div class="fishery-list">
                    <div 
                      v-for="fishery in fisheryList" 
                      :key="fishery.id" 
                      class="fishery-item"
                    >
                      <div class="fishery-info">
                        <div class="fishery-id">ID: {{ fishery.id }}</div>
                        <div class="fishery-name">{{ fishery.name }}</div>
                        <div class="fishery-location">{{ fishery.location }}</div>
                      </div>
                    </div>
                  </div>
                </div>
              </template>
            </SubtitledSectionLong>
          </div>
          <div style="width: 49.5%;margin-left: 0.6rem;">
            <SubtitledSectionLong title="渔场捕捞量">
              <template>
                <div class="catch-volume-wrapper">
                  <div class="time-range-selector">
                    <div 
                      class="time-range-btn" 
                      :class="{ active: catchVolumeTimeRange === 'week' }"
                      @click="changeTimeRange('week')"
                    >
                      近一周
                    </div>
                    <div 
                      class="time-range-btn" 
                      :class="{ active: catchVolumeTimeRange === 'month' }"
                      @click="changeTimeRange('month')"
                    >
                      近一月
                    </div>
                    <div 
                      class="time-range-btn" 
                      :class="{ active: catchVolumeTimeRange === 'year' }"
                      @click="changeTimeRange('year')"
                    >
                      近一年
                    </div>
                    <div 
                      class="time-range-btn" 
                      :class="{ active: catchVolumeTimeRange === 'custom' }"
                      @click="changeTimeRange('custom')"
                    >
                      自定义
                    </div>
                  </div>
                  <div v-if="catchVolumeTimeRange === 'custom'" class="custom-date-range-picker">
                    <input 
                      type="date" 
                      v-model="catchVolumeCustomDateRange.startDate"
                      @change="generateCustomCatchVolumeData"
                      class="date-input"
                      placeholder="开始日期"
                    />
                    <span class="date-separator">至</span>
                    <input 
                      type="date" 
                      v-model="catchVolumeCustomDateRange.endDate"
                      @change="generateCustomCatchVolumeData"
                      class="date-input"
                      placeholder="结束日期"
                    />
                  </div>
                  <div id="catch-volume-chart" class="catch-volume-chart"></div>
                </div>
              </template>
            </SubtitledSectionLong>
          </div>
        </div>
      </div>
      <div class="home-sidebar ">
        <div style="height: 32.8%;">
          <SubtitledSection title="分级捕捞饼状图" style="pointer-events: auto;">
            <template>
              <div class="graded-catch-wrapper">
                <!-- 左上方图例 -->
                <!-- <div class="graded-catch-legend">
                  <div class="legend-item">
                    <span class="legend-color" style="background-color: #5CA0B1;"></span>
                    <span class="legend-text">大</span>
                  </div>
                  <div class="legend-item">
                    <span class="legend-color" style="background-color: #99BB6D;"></span>
                    <span class="legend-text">中</span>
                  </div>
                  <div class="legend-item">
                    <span class="legend-color" style="background-color: #6C8CBC;"></span>
                    <span class="legend-text">小</span>
                  </div>
                </div> -->
                <!-- 右上方时间范围选择器 -->
                <div class="graded-catch-time-selector">
                  <div 
                    class="time-range-btn-small" 
                    :class="{ active: gradedCatchTimeRange === 'week' }"
                    @click="changeGradedCatchTimeRange('week')"
                  >
                    近一周
                  </div>
                  <div 
                    class="time-range-btn-small" 
                    :class="{ active: gradedCatchTimeRange === 'month' }"
                    @click="changeGradedCatchTimeRange('month')"
                  >
                    近一月
                  </div>
                  <div 
                    class="time-range-btn-small" 
                    :class="{ active: gradedCatchTimeRange === 'year' }"
                    @click="changeGradedCatchTimeRange('year')"
                  >
                    近一年
                  </div>
                  <div 
                    class="time-range-btn-small" 
                    :class="{ active: gradedCatchTimeRange === 'custom' }"
                    @click="changeGradedCatchTimeRange('custom')"
                  >
                    自定义
                  </div>
                </div>
                <div v-if="gradedCatchTimeRange === 'custom'" class="custom-date-range-picker-small">
                  <input 
                    type="date" 
                    v-model="gradedCatchCustomDateRange.startDate"
                    @change="generateCustomGradedCatchData"
                    class="date-input-small"
                    placeholder="开始日期"
                  />
                  <span class="date-separator-small">至</span>
                  <input 
                    type="date" 
                    v-model="gradedCatchCustomDateRange.endDate"
                    @change="generateCustomGradedCatchData"
                    class="date-input-small"
                    placeholder="结束日期"
                  />
                </div>
                <!-- 饼状图容器 -->
                <div id="graded-catch-chart" class="graded-catch-chart"></div>
              </div>
            </template>
            
          </SubtitledSection>
        </div>
        <div style="height: 32.8%;">
          <SubtitledSection title="捕捞量折线图" style="pointer-events: auto;">
            <template>
              <div class="catch-line-wrapper">
                <!-- 右上方时间范围选择器 -->
                <div class="catch-line-time-selector">
                  <div 
                    class="time-range-btn-small" 
                    :class="{ active: catchLineTimeRange === 'week' }"
                    @click="changeCatchLineTimeRange('week')"
                  >
                    近一周
                  </div>
                  <div 
                    class="time-range-btn-small" 
                    :class="{ active: catchLineTimeRange === 'month' }"
                    @click="changeCatchLineTimeRange('month')"
                  >
                    近一月
                  </div>
                  <div 
                    class="time-range-btn-small" 
                    :class="{ active: catchLineTimeRange === 'year' }"
                    @click="changeCatchLineTimeRange('year')"
                  >
                    近一年
                  </div>
                  <div 
                    class="time-range-btn-small" 
                    :class="{ active: catchLineTimeRange === 'custom' }"
                    @click="changeCatchLineTimeRange('custom')"
                  >
                    自定义
                  </div>
                </div>
                <div v-if="catchLineTimeRange === 'custom'" class="custom-date-range-picker-small">
                  <input 
                    type="date" 
                    v-model="catchLineCustomDateRange.startDate"
                    @change="generateCustomCatchLineData"
                    class="date-input-small"
                    placeholder="开始日期"
                  />
                  <span class="date-separator-small">至</span>
                  <input 
                    type="date" 
                    v-model="catchLineCustomDateRange.endDate"
                    @change="generateCustomCatchLineData"
                    class="date-input-small"
                    placeholder="结束日期"
                  />
                </div>
                <!-- 折线图容器 -->
                <div id="catch-line-chart" class="catch-line-chart"></div>
              </div>
            </template>
            
          </SubtitledSection>
        </div>
        <div style="height: 32.8%;">
          
        </div>
      </div>
    </div>
  </div>

</template>


<style lang="less" scoped>
::v-deep .camera-label {
  background-image: url('~@/assets/ui/position-text-bg1.png');
  /* 摄像头标签背景 */
  background-size: 100% 100%;
  background-repeat: no-repeat;
  color: #FFFFFF;
  font-family: PingFang SC;
  font-weight: 600;
  font-size: 18px;
}

.time-container {
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #6C8CBC;
  line-height: 15px;
}

/deep/ .amap-icon {
  cursor: pointer !important;
  pointer-events: auto !important;
}

.video-wrapper {
  pointer-events: auto;
  width: calc(100% - 2.6rem);
  height: calc(100% - 2.6rem);
  padding: 0.5rem 1.3rem 1.3rem 1.3rem;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.video-content {
  width: 100%;
  height: 100%;
  object-fit: contain;
  max-width: 100%;
  max-height: 100%;
}

.right-item1-bg {
  width: 100%;
  height: 100%;
  background-image: url('~@/assets/ui/water_quality.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  gap: 5px 90px; // 如果您想在四个部分之间添加一些间距

  >div {

    display: flex;
    flex-direction: column;
    justify-content: center;

    div:first-child {
      height: 30%;
      text-align: center;
      font-family: PingFang SC;
      font-weight: 600;
      font-size: 18px;
      color: #FFFFFF;
    }

    div:last-child {
      height: 30%;
      text-align: center;
      font-family: PingFang SC;
      font-weight: 400;
      font-size: 14px;
      color: #6C8CBC;
    }
  }
}

.right-item1 {
  padding: 2px 0 2px 0;
  height: calc(20% - 4px);
}

.shebei1 {
  height: calc(20.5% - 12px);
}

.shebei2 {
  height: calc(20.0% - 8px);
}

.right-item2 {
  // border: 1px red solid;
  padding: 4px 0 4px 0;
  font-family: Source Han Sans CN;
  font-weight: 800;
  font-size: 18px;
  color: #FFFFFF;
  display: flex;
  flex-direction: column;

  span {
    flex: 0 0;
    line-height: 18px;
  }

  div {
    flex: 1 1;
  }
}

::v-deep .amap-marker-label {
  border: 0;
  background-color: transparent;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  font-family: PingFang SC;
  font-weight: 600;
  font-size: 18px;
  color: #FFFFFF;
  // line-height: 41px;
  text-stroke: 1px #000000;
  -webkit-text-stroke: 1px #000000;
}

::v-deep .water-quality-label {
  background-image: url('~@/assets/ui/position-text-bg.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
}

::v-deep .meteorological-label {
  background-image: url('~@/assets/ui/position-text-bg2.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
}

// /deep/.amap-marker-label {
//   border: 0;
//   background-color: rgba(54, 74, 112, 0.4);
//   padding: 10px;
//   // background-image: url('~@/assets/ui/position-text-bg.png');
//   background-size: 100% 100%;
//   background-repeat: no-repeat;
//   font-family: PingFang SC;
//   font-weight: 600;
//   font-size: 18px;
//   color: #FFFFFF;
//   // line-height: 41px;
//   text-stroke: 1px #000000;

//   -webkit-text-stroke: 1px #000000;
// }


//  地图设备提示框样式
.equip-box {
  position: absolute;
  top: 43%;
  /* 改为 50% */
  left: 50%;
  transform: translate(-50%, -50%);
  /* 添加这行，使元素居中 */
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 16px;
  // color: #F4ECC4;
  line-height: 32px;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  width: 25rem;
  // height: 18rem;


  // img {
  //   width: 22.2rem;
  // }

  .text {
    position: absolute;
    top: 0;
    left: 0;
    padding: 1rem 1rem;
  }


  .info-table {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
  }

  .info-row {
    display: flex;
    width: 50%;
    margin-bottom: 0.5rem;

    &.full-width {
      width: 100%;
    }
  }

  .info-label {
    width: 5rem; // 设置固定宽度，可以根据需要调整
    margin-right: 0.5rem;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: space-between;
    white-space: nowrap;
    overflow: hidden;

    &::after {
      content: ':';
      margin-left: 0.2rem;
    }
  }

  .info-label span {
    display: inline-block;
    width: 100%;
    text-align: justify;
    text-align-last: justify;
    letter-spacing: 0.1em; // 调整字间距以实现等距效果

    font-family: PingFang SC;
    font-weight: 400;
    font-size: 17px;

    &::after {
      content: '';
      display: inline-block;
      width: 100%;
    }
  }

  .info-value {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

    font-family: PingFang SC;
    font-weight: 400;
    font-size: 17px;
    // color: #5CA0B1;//#c6e1e7
    // line-height: 28px;
  }

  .close-icon {
    position: absolute;
    top: -2.5rem;
    right: 0rem;
    width: 2.4rem;
    height: 2.4rem;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 0.3rem;
  }

  /*item框的高度*/
  .h-35 {
    height: 35%;
  }

  /*左下角设备描述字体*/

}

.header {
  width: 100%;
  height: 6rem;
}

.main {
  width: calc(100% - 2.7rem);
  height: calc(100% - 8.7rem);
  padding: 1.35rem;
  color: black;
  position: relative;
  pointer-events: none;

}

.home-sidebar {
  pointer-events: auto;
  height: 100%;
  // height: calc(100vh-11.4rem);
  width: 22.5%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  div {
    width: 100%;
  }

}

.home-center {
  height: 100%;
  width: 55%;
  position: relative;
  padding-left: 0.5rem;
  padding-right: 0.5rem;
  pointer-events: none;
}

.info-box {
  margin-top: 1.6rem;
  height: 5%;
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.info-item {
  width: 12%;
  height: 100%;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  display: flex;
  // justify-content: flex-end;
  align-items: center;
  font-family: PingFang SC;
  font-weight: 600;
  font-size: 20px;
  color: #FFFFFF;
  line-height: 41px;
}


.bottom-box {
  height: 32.6%;
  width: calc(100% - 1rem);
  margin-top: 1.5rem;
  position: absolute;
  display: flex;
  flex-direction: row;
  bottom: 0;

}

.box {
  background-image: url("~@/assets/ui/bg.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
}

.fishery-list-wrapper {
  pointer-events: auto;
  width: calc(100% - 2.6rem);
  height: calc(100% - 2.6rem);
  padding: 0.5rem 1.3rem 1.3rem 1.3rem;
  overflow-y: auto;
  overflow-x: hidden;
  scroll-behavior: smooth;
  position: relative;
  /* 隐藏滚动条但保持滚动功能 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

.fishery-list-wrapper::-webkit-scrollbar {
  display: none; /* Chrome, Safari, Opera */
}

.fishery-list {
  display: flex;
  flex-direction: column;
  gap: 0.8rem;
}

.fishery-item {
  background: rgba(54, 74, 112, 0.3);
  border: 1px solid rgba(108, 140, 188, 0.3);
  border-radius: 0.4rem;
  padding: 0.8rem 1rem;
  transition: all 0.3s ease;
}

.fishery-item:hover {
  background: rgba(54, 74, 112, 0.5);
  border-color: rgba(108, 140, 188, 0.6);
  transform: translateX(0.2rem);
}

.fishery-info {
  display: flex;
  flex-direction: column;
  gap: 0.4rem;
}

.fishery-id {
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 12px;
  color: #6C8CBC;
  line-height: 1.2;
}

.fishery-name {
  font-family: PingFang SC;
  font-weight: 600;
  font-size: 16px;
  color: #FFFFFF;
  line-height: 1.4;
}

.fishery-location {
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #6C8CBC;
  line-height: 1.3;
}

.catch-volume-wrapper {
  pointer-events: auto;
  width: calc(100% - 2.6rem);
  height: calc(100% - 2.6rem);
  padding: 0.5rem 1.3rem 1.3rem 1.3rem;
  position: relative;
  display: flex;
  flex-direction: column;
}

.time-range-selector {
  display: flex;
  justify-content: flex-end;
  gap: 0.8rem;
  margin-bottom: 0.5rem;
  z-index: 10;
}

.time-range-btn {
  padding: 0.4rem 1rem;
  background: rgba(54, 74, 112, 0.3);
  border: 1px solid rgba(108, 140, 188, 0.3);
  border-radius: 0.3rem;
  color: #6C8CBC;
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  user-select: none;
}

.time-range-btn:hover {
  background: rgba(54, 74, 112, 0.5);
  border-color: rgba(108, 140, 188, 0.6);
  color: #FFFFFF;
}

.time-range-btn.active {
  background: rgba(92, 160, 177, 0.6);
  border-color: rgba(92, 160, 177, 0.8);
  color: #FFFFFF;
  font-weight: 600;
}

.catch-volume-chart {
  flex: 1;
  width: 100%;
  min-height: 0;
}

.graded-catch-wrapper {
  pointer-events: auto;
  width: calc(100% - 2.6rem);
  height: calc(100% - 2.6rem);
  padding: 0.5rem 1.3rem 1.3rem 1.3rem;
  position: relative;
  display: flex;
  flex-direction: column;
}

.graded-catch-legend {
  position: absolute;
  top: 0.5rem;
  left: 1.3rem;
  display: flex;
  gap: 1rem;
  z-index: 10;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 0.4rem;
}

.legend-color {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 2px;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.legend-text {
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 12px;
  color: #6C8CBC;
  line-height: 1.2;
}

.graded-catch-time-selector {
  position: absolute;
  top: 0.5rem;
  right: 1.3rem;
  display: flex;
  gap: 0.5rem;
  z-index: 10;
}

.time-range-btn-small {
  padding: 0.25rem 0.6rem;
  background: rgba(54, 74, 112, 0.3);
  border: 1px solid rgba(108, 140, 188, 0.3);
  border-radius: 0.2rem;
  color: #6C8CBC;
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 11px;
  cursor: pointer;
  transition: all 0.3s ease;
  user-select: none;
  white-space: nowrap;
}

.time-range-btn-small:hover {
  background: rgba(54, 74, 112, 0.5);
  border-color: rgba(108, 140, 188, 0.6);
  color: #FFFFFF;
}

.time-range-btn-small.active {
  background: rgba(92, 160, 177, 0.6);
  border-color: rgba(92, 160, 177, 0.8);
  color: #FFFFFF;
  font-weight: 600;
}

.graded-catch-chart {
  flex: 1;
  width: 100%;
  min-height: 0;
  margin-top: 1.5rem;
}

/* 当显示自定义日期选择器时,调整图表位置 */
.graded-catch-wrapper:has(.custom-date-range-picker-small) .graded-catch-chart {
  margin-top: 3.5rem;
}

.catch-line-wrapper {
  pointer-events: auto;
  width: calc(100% - 2.6rem);
  height: calc(100% - 2.6rem);
  padding: 0.5rem 1.3rem 1.3rem 1.3rem;
  position: relative;
  display: flex;
  flex-direction: column;
}

.catch-line-time-selector {
  position: absolute;
  top: 0.5rem;
  right: 1.3rem;
  display: flex;
  gap: 0.5rem;
  z-index: 10;
}

.catch-line-chart {
  flex: 1;
  width: 100%;
  min-height: 0;
  margin-top: 3rem;
  padding-top: 0.5rem;
}

/* 当显示自定义日期选择器时,调整折线图位置 */
.catch-line-wrapper:has(.custom-date-range-picker-small) .catch-line-chart {
  margin-top: 4.5rem;
}

/* 自定义日期范围选择器样式 */
.custom-date-range-picker {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 0.5rem;
  margin-bottom: 0.5rem;
  z-index: 10;
}

.date-input {
  padding: 0.4rem 0.8rem;
  background: rgba(54, 74, 112, 0.3);
  border: 1px solid rgba(108, 140, 188, 0.3);
  border-radius: 0.3rem;
  color: #FFFFFF;
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 12px;
  outline: none;
  transition: all 0.3s ease;
}

.date-input:hover {
  background: rgba(54, 74, 112, 0.5);
  border-color: rgba(108, 140, 188, 0.6);
}

.date-input:focus {
  background: rgba(54, 74, 112, 0.6);
  border-color: rgba(92, 160, 177, 0.8);
}

.date-separator {
  color: #6C8CBC;
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 12px;
}

/* 小尺寸日期选择器样式（用于饼状图和折线图） */
.custom-date-range-picker-small {
  position: absolute;
  top: 2.5rem;
  right: 1.3rem;
  display: flex;
  align-items: center;
  gap: 0.4rem;
  z-index: 10;
}

.date-input-small {
  padding: 0.25rem 0.5rem;
  background: rgba(54, 74, 112, 0.3);
  border: 1px solid rgba(108, 140, 188, 0.3);
  border-radius: 0.2rem;
  color: #FFFFFF;
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 10px;
  outline: none;
  transition: all 0.3s ease;
  width: 100px;
}

.date-input-small:hover {
  background: rgba(54, 74, 112, 0.5);
  border-color: rgba(108, 140, 188, 0.6);
}

.date-input-small:focus {
  background: rgba(54, 74, 112, 0.6);
  border-color: rgba(92, 160, 177, 0.8);
}

.date-separator-small {
  color: #6C8CBC;
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 10px;
}

/* 日期输入框的占位符样式 */
.date-input::-webkit-calendar-picker-indicator {
  filter: invert(1);
  cursor: pointer;
}

.date-input-small::-webkit-calendar-picker-indicator {
  filter: invert(1);
  cursor: pointer;
}

.trace-records-dialog {
  background: rgba(1, 10, 20, 0.95);
  border: 1px solid rgba(67, 200, 255, 0.3);
}

.trace-records-container {
  max-height: 500px;
  overflow-y: auto;
}

.trace-record-meta {
  display: flex;
  gap: 1.5rem;
  margin-bottom: 1rem;
  color: #C3E4FF;
  font-size: 14px;
}

.trace-detail-dialog {
  background: rgba(1, 10, 20, 0.95);
  border: 1px solid rgba(67, 200, 255, 0.3);
}

.trace-detail-content {
  color: #C3E4FF;
}

.trace-temperature-chart-container {
  margin-bottom: 1rem;
}

.trace-temperature-chart {
  width: 100%;
  height: 260px;
}

.trace-temperature-chart-container .chart-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 0.5rem;
  color: #C3E4FF;
}

.trace-detail-text .el-textarea__inner {
  background: rgba(12, 30, 60, 0.55);
  color: #C3E4FF;
  border-color: rgba(85, 150, 223, 0.4);
}

</style>
